package com.ramblingcoder.bc2.server.tool.update;

import java.io.IOException;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.ramblingcoder.bc2.server.tool.update.R;
import com.ramblingcoder.bc2.server.tool.update.commands.SupportingFunctions;
import com.ramblingcoder.bc2.server.tool.update.exceptions.AccessError;
import com.ramblingcoder.bc2.server.tool.update.exceptions.InvalidArguments;
import com.ramblingcoder.bc2.server.tool.update.exceptions.LogInRequired;
import com.ramblingcoder.bc2.server.tool.update.exceptions.NotFound;
import com.ramblingcoder.bc2.server.tool.update.objects.Ban;
import com.ramblingcoder.bc2.server.tool.update.objects.InfoShare;

public class BanView extends Activity implements OnClickListener {
	//Variables-----\
	private Button clear;
	private Button save;
	//Variables-----/
	
	//Initializer-----\
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
        setContentView(R.layout.banview);
        
        clear = (Button) findViewById(R.id.clear);
        clear.setOnClickListener(this);
        
        save = (Button) findViewById(R.id.save);
        save.setOnClickListener(this);
        
        try {
			populate();
		} catch (InvalidArguments e) {
			SupportingFunctions.showError(this, e.getMessage(), new Intent(this, BC2ServerChoice.class));
		} catch (LogInRequired e) {
			SupportingFunctions.showError(this, e.getMessage(), new Intent(this, BC2ServerChoice.class));
		} catch (IOException e) {
			SupportingFunctions.showError(this, e.getMessage(), new Intent(this, BC2ServerChoice.class));
		}
	}
	
	public boolean onCreateOptionsMenu(Menu menu) {
	    menu.add(1, 5, 0, "Main Menu");
	    menu.add(1, 0, 0, "Refresh");
	    menu.add(1, 1, 0, "Players View");
	    menu.add(1, 2, 0, "Map View");
	    menu.add(1, 3, 0, "Settings View");
	    menu.add(1, 4, 0, "Chat View");
	    menu.add(1, 6, 0, "Reserved View");
	    return true;
	}
	
	public boolean onOptionsItemSelected(MenuItem item) {
	    switch (item.getItemId()) {
	    case 5:
	    	finish();
	    	startActivity(new Intent(this, BC2ServerChoice.class));
	    	break;
	    case 0:
	    	finish();
	    	startActivity(new Intent(this, BanView.class));
	    	break;
	    case 1:	
	    	finish();
	    	startActivity(new Intent(this, PlayerView.class));
	    	break;
	    case 2:
	    	finish();
	    	startActivity(new Intent(this, MapView.class));
	    	break;
	    case 3:
	    	finish();
	    	startActivity(new Intent(this, SettingsView.class));
	    	break;
	    case 4:
	    	finish();
	    	startActivity(new Intent(this, ChatView.class));
	    	break;
	    case 6:
	    	finish();
	    	startActivity(new Intent(this, ReservedView.class));
	    	break;
	    }
	    return true;
	}

	private void populate() throws InvalidArguments, LogInRequired, IOException {
		Ban[] bans = Ban.listBans(InfoShare.getCommand());
		
		LinearLayout layout = (LinearLayout) findViewById(R.id.banlist);
		
		LayoutInflater li = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		
		for (int i = 0; i < bans.length; i++){
			final Ban ban = bans[i];
			
			LinearLayout banLayout = new LinearLayout(this);
			li.inflate(R.layout.banrow, banLayout);

			if (i % 2 == 0)	banLayout.setBackgroundColor(Color.parseColor("#333333"));
			else banLayout.setBackgroundColor(Color.parseColor("#000000"));
			
			TextView name = ((TextView) banLayout.findViewById(R.id.name));
			TextView ip = ((TextView) banLayout.findViewById(R.id.ip));
			TextView guid = ((TextView) banLayout.findViewById(R.id.guid));

			TextView duration = ((TextView) banLayout.findViewById(R.id.duration));
			TextView notes = ((TextView) banLayout.findViewById(R.id.note));

			((LinearLayout) banLayout.findViewById(R.id.iplayout)).setVisibility(View.GONE);
			((LinearLayout) banLayout.findViewById(R.id.guidlayout)).setVisibility(View.GONE);
			((LinearLayout) banLayout.findViewById(R.id.namelayout)).setVisibility(View.GONE);
			
			if (ban.getIdType().equals("name")){
				((LinearLayout) banLayout.findViewById(R.id.namelayout)).setVisibility(View.VISIBLE);
				name.setText(ban.getId());
			} else if (ban.getIdType().equals("ip")){
				((LinearLayout) banLayout.findViewById(R.id.iplayout)).setVisibility(View.VISIBLE);
				ip.setText(ban.getId());
			} else if (ban.getIdType().equals("guid")){
				((LinearLayout) banLayout.findViewById(R.id.guidlayout)).setVisibility(View.VISIBLE);
				guid.setText(ban.getId());
			}
			
			
			if (ban.getBanType().equals("perm"))
				duration.setText("Permanent");
			else if (ban.getBanType().equals("round"))
				duration.setText("Round");
			else
				duration.setText(ban.getTimeFormatted());
		
			notes.setText(ban.getReason());
			
			layout.addView(banLayout);
			
			banLayout.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					unban(ban);
				}
			});
		}
	}

	private void unban(final Ban ban) {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		
		builder.setTitle("Unban Confirmation");

        builder.setMessage("Unban " + ban.getId() + "?");
        
        builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
		        try {
		        	if (Ban.unban(InfoShare.getCommand(), ban.getIdType(), ban.getId()))
		        		SupportingFunctions.showMessage(BanView.this, "Success", "Ban successfully removed.", new Intent(BanView.this, BanView.class));
				} catch (IOException e) {
					SupportingFunctions.showError(BanView.this, e.getMessage(), new Intent(BanView.this, BC2ServerChoice.class));
				} catch (InvalidArguments e) {
					SupportingFunctions.showError(BanView.this, e.getMessage());
				} catch (LogInRequired e) {
					SupportingFunctions.showError(BanView.this, e.getMessage(), new Intent(BanView.this, BC2ServerChoice.class));
				} catch (NotFound e) {
					SupportingFunctions.showError(BanView.this, e.getMessage());
				}	
			}
		}); 
		
        builder.setNegativeButton("No", null); 
		
        builder.show(); 
	}
	//Initializer-----/

	//Events-----\
	public void onClick(View v) {
		if (v.getId() == R.id.clear){
			clearBans();
		} else if (v.getId() == R.id.save){
			saveBans();
		}
	}
	
    public boolean onKeyDown(int keyCode, KeyEvent event)  {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
        	finish();
        	startActivity(new Intent(this, PlayerView.class));
            return true;
        }

        return super.onKeyDown(keyCode, event);
    }
	//Events-----/

	//Processes-----\
	private void clearBans() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		
		builder.setTitle("Clear All Bans?");
		builder.setMessage("Are you sure?");
		
        builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				try {
					if (Ban.clear(InfoShare.getCommand()))
						SupportingFunctions.showMessage(BanView.this, "Success", "Bans cleared successfully.", new Intent(BanView.this, BanView.class));
				} catch (IOException e) {
					SupportingFunctions.showError(BanView.this, e.getMessage(), new Intent(BanView.this, BC2ServerChoice.class));
				} catch (LogInRequired e) {
					SupportingFunctions.showError(BanView.this, e.getMessage(), new Intent(BanView.this, BC2ServerChoice.class));
				} catch (InvalidArguments e) {
					SupportingFunctions.showError(BanView.this, e.getMessage());
				}
			}
		}); 
        
        builder.setNegativeButton("Cancel", null); 
		
        builder.show(); 
	}
	
	private void saveBans() {
		try {
			if (Ban.save(InfoShare.getCommand()))
				SupportingFunctions.showMessage(BanView.this, "Success", "Bans saved successfully.", new Intent(BanView.this, BanView.class));
		} catch (IOException e) {
			SupportingFunctions.showError(BanView.this, e.getMessage(), new Intent(BanView.this, BC2ServerChoice.class));
		} catch (LogInRequired e) {
			SupportingFunctions.showError(BanView.this, e.getMessage(), new Intent(BanView.this, BC2ServerChoice.class));
		} catch (InvalidArguments e) {
			SupportingFunctions.showError(BanView.this, e.getMessage());
		} catch (AccessError e) {
			SupportingFunctions.showError(BanView.this, e.getMessage());
		}
	}
	//Processes-----/
}
